package com.urfresh.sp.user.restapi;

import com.baidu.disconf.client.common.annotations.DisconfFile;
import com.baidu.disconf.client.common.annotations.DisconfFileItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.text.SimpleDateFormat;
import java.util.Date;


@RestController
@DisconfFile(filename = "urfresh_bind_user.properties")
public class UserCheckController {

    /**
     * 用来判断每个手机最多允许绑定的手机，如果超过这个数，就认为是黄牛
     */
    int num = 3;

    @DisconfFileItem(name = "num")
    public int getNum() {
        return num;
    }

    @Autowired
    JedisPool pool;


    protected Logger logger = LoggerFactory.getLogger(UserCheckController.class);

    @RequestMapping(value = "/isFakeUser/{type}/{userName}", method = RequestMethod.GET)
    public String check(@PathVariable String type, @PathVariable String userName) {

        logger.info("判断是否黄牛用户:" + type + ",userName=" + userName);
        //如果不是手机号，判断为不是黄牛用户
        if (userName.length() != 11)
            return "false";

        String traffic_bind_user_num = "";
        try (Jedis jedis = pool.getResource()) {
            traffic_bind_user_num = jedis.hget("userName:" + userName, "traffic_bind_user_num");
        }

        int userNum = 0;
        if(StringUtils.isEmpty(traffic_bind_user_num)==false)
            userNum = Integer.valueOf(traffic_bind_user_num);

        //判断是否大于规定的数量
        if (userNum >= num) {
            logger.info("hit! 查询到黄牛用户," + userName);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            //当天命中的用户数量+1
            try(Jedis jedis=pool.getResource()){
                jedis.incr("hit:"+format.format(new Date()));
            }
            return "true";
        }

        return "false";
    }



}
